package com.nsgf.library.ui.page;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.DutyManagerBean;
import com.nsgf.library.data.bean.DutyScheduleBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityDutyManagementBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.widget.prckerview.TimePickerView;

import java.util.HashMap;
import java.util.Map;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 值班管理页面
 */
public class DutyManagementActivity extends BaseActivity {

    DutyManagementStates states;
    private ActivityDutyManagementBinding mBinding;

    private Calendar currentCalendar;
    private List<CalendarDay> calendarDays = new ArrayList<>();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.getDefault());
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM", Locale.getDefault());
    private SimpleDateFormat dayFormat = new SimpleDateFormat("d", Locale.getDefault());

    private AccountRequester mAccountRequester;

    // 当天日期
    private int todayYear;
    private int todayMonth;
    private int todayDay;

    // 值班日期Map，key: 日期(yyyy-MM-dd), value: DutyScheduleBean
    private Map<String, DutyScheduleBean> dutyDateMap = new HashMap<>();

    // 日期选择回调接口
    public interface OnDateSelectedListener {
        void onDateSelected(int year, int month, int day);
    }

    private OnDateSelectedListener dateSelectedListener;

    public void setOnDateSelectedListener(OnDateSelectedListener listener) {
        this.dateSelectedListener = listener;
    }

    @Override
    protected void initViewModel() {
        states = getActivityScopeViewModel(DutyManagementStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_duty_management, BR.vm, states)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityDutyManagementBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);
        // 初始化当前日期
        currentCalendar = Calendar.getInstance();
        int currentYear = currentCalendar.get(Calendar.YEAR);
        int currentMonth = currentCalendar.get(Calendar.MONTH);
        int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);

        // 保存当天日期
        todayYear = currentYear;
        todayMonth = currentMonth;
        todayDay = currentDay;

        // 显示当前月份
        states.monthYear.set(dateFormat.format(currentCalendar.getTime()));
        states.totalDutyDays.set("共排班 0 天");

        // 初始化时间
        states.startTime.set(String.format(Locale.getDefault(), "%04d-%02d", currentYear, currentMonth + 1));

        // 设置标题
        states.titleBar.set("值班管理");

        // 初始化日历
        generateCalendarDays(currentYear, currentMonth);
        states.selectedDay.set(currentDay);

        // 创建并绘制日历视图
        createCalendarView();

        // 默认选择当天（此时数据可能还没加载，但可以先显示基本样式）
        selectDay(currentYear, currentMonth, currentDay);

        mAccountRequester.scheduleList(UserInfo.getInstance().getProjectCode(), states.monthYear.get());

        mAccountRequester.getDutyManagerResult().observe(this, new Observer<ResponseStatus<List<DutyManagerBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<DutyManagerBean>> listResponseStatus) {
                if (listResponseStatus != null && listResponseStatus.getResponseCode() == 200) {
                    List<DutyManagerBean> dataList = listResponseStatus.getData();
                    if (dataList != null) {
                        list = dataList;
                        // 将DutyManagerBean转换为DutyScheduleBean并更新日历
                        updateDutySchedulesFromManagerList(list);
                    }
                }
            }
        });
    }

    List<DutyManagerBean> list = new ArrayList<>();

    /**
     * 生成日历天数
     */
    private void generateCalendarDays(int year, int month) {
        calendarDays.clear();

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 1);

        // 获取当月第一天是星期几 (1=Sunday, 2=Monday, ...)
        int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 转换为我们的格式 (0=Sunday, 1=Monday, ...)
        int startOffset = firstDayOfWeek == Calendar.SUNDAY ? 0 : firstDayOfWeek - 1;

        // 获取上个月的最后几天
        calendar.add(Calendar.DAY_OF_MONTH, -startOffset);
        for (int i = 0; i < startOffset; i++) {
            CalendarDay day = new CalendarDay(
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    false
            );
            calendarDays.add(day);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 获取当月日期
        calendar.set(year, month, 1);
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int i = 1; i <= daysInMonth; i++) {
            CalendarDay day = new CalendarDay(year, month, i, true);
            calendarDays.add(day);
        }

        // 获取下个月的前几天，补齐42个格子（6周）
        int remainingDays = 42 - calendarDays.size();
        calendar.add(Calendar.MONTH, 1);
        for (int i = 0; i < remainingDays; i++) {
            CalendarDay day = new CalendarDay(
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    false
            );
            calendarDays.add(day);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 刷新日历显示
        updateCalendarDisplay();
    }

    /**
     * 创建日历视图
     */
    private void createCalendarView() {
        ViewGroup calendarContainer = mBinding.calendarContainer;
        calendarContainer.removeAllViews();

        // 添加星期标题
        LinearLayout weekLayout = new LinearLayout(this);
        weekLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams weekLayoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );

        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        for (String day : weekDays) {
            TextView textView = new TextView(this);
            textView.setText(day);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(getResources().getColor(R.color.color_4E5969));
            textView.setTextSize(14);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, dpToPx(40));
            params.weight = 1;
            textView.setLayoutParams(params);
            weekLayout.addView(textView);
        }

        calendarContainer.addView(weekLayout, weekLayoutParams);

        // 添加日历网格 (6行 x 7列)
        for (int row = 0; row < 6; row++) {
            LinearLayout dayRow = new LinearLayout(this);
            dayRow.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            rowParams.setMargins(0, dpToPx(3), 0, dpToPx(3)); // 添加上下间距

            for (int col = 0; col < 7; col++) {
                // 创建一个容器来放置日期和标识
                LinearLayout dayContainer = new LinearLayout(this);
                dayContainer.setOrientation(LinearLayout.VERTICAL);
                dayContainer.setGravity(Gravity.CENTER);
                dayContainer.setPadding(dpToPx(4), dpToPx(4), dpToPx(4), dpToPx(4));

                // 设置圆角背景
                android.graphics.drawable.GradientDrawable bg = new android.graphics.drawable.GradientDrawable();
                bg.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
                bg.setCornerRadius(dpToPx(4));
                dayContainer.setBackgroundDrawable(bg);

                // 日期TextView
                TextView dayView = new TextView(this);
                dayView.setGravity(Gravity.CENTER);
                dayView.setTextSize(14);

                // 值班日标识TextView
                TextView dutyTagView = new TextView(this);
                dutyTagView.setGravity(Gravity.CENTER);
                dutyTagView.setTextSize(9);
                dutyTagView.setTextColor(getResources().getColor(R.color.color_1D2129));
                dutyTagView.setBackgroundColor(getResources().getColor(R.color.color_FAB786));
                dutyTagView.setVisibility(View.GONE);
                dutyTagView.setPadding(dpToPx(4), dpToPx(2), dpToPx(4), dpToPx(2));

                int position = row * 7 + col;
                if (position < calendarDays.size()) {
                    CalendarDay day = calendarDays.get(position);
                    dayView.setText(String.valueOf(day.day));
                    dayView.setTag("day_" + position); // 添加tag以便后续查找

                    // 存储日期信息到dayContainer的tag中
                    dayContainer.setTag(day);

                    if (day.isCurrentMonth) {
                        dayView.setTextColor(getResources().getColor(R.color.color_1D2129));
                        dayView.setBackground(null);

                        // 设置点击监听
                        dayContainer.setOnClickListener(v -> {
                            CalendarDay clickedDay = (CalendarDay) v.getTag();
                            selectDay(clickedDay.year, clickedDay.month, clickedDay.day);
                        });
                    } else {
                        dayView.setTextColor(getResources().getColor(R.color.light_gray));
                        dayView.setBackground(null);
                    }
                }

                // 将日期和标识添加到容器
                dayContainer.addView(dayView);
                dayContainer.addView(dutyTagView);

                // 计算宽度，然后设置为正方形
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                int cellWidth = (screenWidth - dpToPx(40)) / 7; // 减去左右padding
                LinearLayout.LayoutParams dayParams = new LinearLayout.LayoutParams(cellWidth, cellWidth);
                dayParams.setMargins(dpToPx(2), dpToPx(2), dpToPx(2), dpToPx(2));
                dayContainer.setLayoutParams(dayParams);
                dayRow.addView(dayContainer);
            }

            calendarContainer.addView(dayRow, rowParams);
        }

        // 不在这里调用updateCalendarDisplay，等数据加载完成后再调用
        // updateCalendarDisplay();
    }

    /**
     * dp 转 px
     */
    private int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    /**
     * 选择日期
     */
    private void selectDay(int year, int month, int day) {
        states.selectedDay.set(day);
        updateCalendarDisplay();

        // 构建日期字符串
        String dateStr = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month + 1, day);

        // 检查是否是值班日
        DutyScheduleBean schedule = getDutySchedule(dateStr);
        if (schedule != null && schedule.getIsDutyDay() == 1) {
            states.dutyStatus.set("值班日");
            String dutyInfo = "";
            if (schedule.getDutyStaffReal() != null && !schedule.getDutyStaffReal().isEmpty()) {
                dutyInfo = "值班人员：" + schedule.getDutyStaffReal() + "\n";
            }
            if (schedule.getDutyLeaderReal() != null && !schedule.getDutyLeaderReal().isEmpty()) {
                dutyInfo += "值班领导：" + schedule.getDutyLeaderReal() + "\n";
            }
            if (schedule.getSuccessorReal() != null && !schedule.getSuccessorReal().isEmpty()) {
                dutyInfo += "接班人：" + schedule.getSuccessorReal() + "\n";
            }
            if (schedule.getSuccessorLeaderReal() != null && !schedule.getSuccessorLeaderReal().isEmpty()) {
                dutyInfo += "接班人领导：" + schedule.getSuccessorLeaderReal();
            }
            states.dutyInfo.set(dutyInfo);
        } else {
            states.dutyStatus.set("非值班日");
            states.dutyInfo.set("");
        }

        // 触发回调
        if (dateSelectedListener != null) {
            dateSelectedListener.onDateSelected(year, month, day);
        }
    }

    /**
     * 判断是否是值班日
     */
    private boolean isDutyDay(String date) {
        DutyScheduleBean schedule = dutyDateMap.get(date);
        boolean result = schedule != null && schedule.getIsDutyDay() == 1;
        if (result) {
            android.util.Log.d("DutyManagement", "找到值班日: " + date);
        }
        return result;
    }

    /**
     * 获取值班信息
     */
    private DutyScheduleBean getDutySchedule(String date) {
        return dutyDateMap.get(date);
    }

    /**
     * 设置值班日期列表
     */
    public void setDutySchedules(List<DutyScheduleBean> schedules) {
        android.util.Log.d("DutyManagement", "setDutySchedules被调用，schedules数量: " + (schedules != null ? schedules.size() : 0));
        dutyDateMap.clear();
        if (schedules != null && !schedules.isEmpty()) {
            for (DutyScheduleBean schedule : schedules) {
                if (schedule != null && schedule.getStartDate() != null) {
                    dutyDateMap.put(schedule.getStartDate(), schedule);
                    android.util.Log.d("DutyManagement", "存储值班日到dutyDateMap: " + schedule.getStartDate() + ", isDutyDay: " + schedule.getIsDutyDay());
                }
            }
        }
        android.util.Log.d("DutyManagement", "dutyDateMap最终大小: " + dutyDateMap.size());
        updateCalendarDisplay();

        // 如果当前选中的日期是值班日，重新选择以更新状态显示
        int selectedDay = states.selectedDay.get();
        if (selectedDay > 0) {
            int year = currentCalendar.get(Calendar.YEAR);
            int month = currentCalendar.get(Calendar.MONTH);
            selectDay(year, month, selectedDay);
        }
    }

    /**
     * 从DutyManagerBean列表更新值班日期
     */
    private void updateDutySchedulesFromManagerList(List<DutyManagerBean> managerList) {
        dutyDaysCount = 0;
        // 将DutyManagerBean列表转换为DutyScheduleBean列表
        List<DutyScheduleBean> scheduleList = new ArrayList<>();
        if (managerList != null && !managerList.isEmpty()) {
            for (DutyManagerBean managerBean : managerList) {
                // 将DutyManagerBean转换为DutyScheduleBean
                DutyScheduleBean scheduleBean = convertToDutyScheduleBean(managerBean);
                if (scheduleBean != null && scheduleBean.getStartDate() != null) {
                    scheduleList.add(scheduleBean);
                    // 调试日志
                    android.util.Log.d("DutyManagement", "添加值班日: " + scheduleBean.getStartDate() + ", isDutyDay: " + scheduleBean.getIsDutyDay());
                }

                if (1 == managerBean.getIsDutyDay()) {
                    dutyDaysCount++;
                }
            }
        }
        // 调用setDutySchedules方法统一处理
        setDutySchedules(scheduleList);
        states.totalDutyDays.set("共排班 " + dutyDaysCount + " 天");
    }

    // 更新排班天数统计
    int dutyDaysCount = 0;

    /**
     * 将DutyManagerBean转换为DutyScheduleBean
     */
    private DutyScheduleBean convertToDutyScheduleBean(DutyManagerBean managerBean) {
        if (managerBean == null) {
            return null;
        }
        DutyScheduleBean scheduleBean = new DutyScheduleBean();
        scheduleBean.setRowCode(managerBean.getRowCode());
        scheduleBean.setProjectCode(managerBean.getProjectCode());
        scheduleBean.setProjectName(managerBean.getProjectName());
        scheduleBean.setUserName(managerBean.getUserName());
        scheduleBean.setLeaderName(managerBean.getLeaderName());
        scheduleBean.setStartDate(managerBean.getStartDate());
        scheduleBean.setIsDutyDay(managerBean.getIsDutyDay());
        scheduleBean.setIsLeader(managerBean.getIsLeader());
        scheduleBean.setDutyStaffReal(managerBean.getDutyStaffReal());
        scheduleBean.setDutyLeaderReal(managerBean.getDutyLeaderReal());
        scheduleBean.setSuccessorReal(managerBean.getSuccessorReal());
        scheduleBean.setSuccessorLeaderReal(managerBean.getSuccessorLeaderReal());

        // 转换BuSchedulingList
        if (managerBean.getBuSchedulingList() != null) {
            List<DutyScheduleBean.BuSchedulingBean> buSchedulingList = new ArrayList<>();
            for (DutyManagerBean.BuSchedulingListBean managerItem : managerBean.getBuSchedulingList()) {
                DutyScheduleBean.BuSchedulingBean schedulingBean = new DutyScheduleBean.BuSchedulingBean();
                schedulingBean.setId(String.valueOf(managerItem.getId()));
                schedulingBean.setProjectCode(managerItem.getProjectCode());
                schedulingBean.setRowCode(managerItem.getRowCode());
                schedulingBean.setUserId(managerItem.getUserId());
                schedulingBean.setUserName(managerItem.getUserName());
                schedulingBean.setIsLeader(managerItem.getIsLeader());
                schedulingBean.setStartDate(managerItem.getStartDate());
                schedulingBean.setDutyStaffReal(managerItem.getDutyStaffReal());
                schedulingBean.setDutyLeaderReal(managerItem.getDutyLeaderReal());
                schedulingBean.setSuccessorReal(managerItem.getSuccessorReal());
                schedulingBean.setSuccessorLeaderReal(managerItem.getSuccessorLeaderReal());
                buSchedulingList.add(schedulingBean);
            }
            scheduleBean.setBuSchedulingList(buSchedulingList);
        }

        return scheduleBean;
    }

    /**
     * 更新日历显示
     */
    private void updateCalendarDisplay() {
        ViewGroup calendarContainer = mBinding.calendarContainer;
        int selectedDay = states.selectedDay.get();

        // 跳过星期标题行（第0个child），从第1个开始是日历网格
        for (int i = 1; i < calendarContainer.getChildCount(); i++) {
            View row = calendarContainer.getChildAt(i);
            if (row instanceof LinearLayout) {
                LinearLayout rowLayout = (LinearLayout) row;
                int rowIndex = i - 1; // 减去星期标题行

                for (int j = 0; j < rowLayout.getChildCount(); j++) {
                    View cell = rowLayout.getChildAt(j);
                    if (cell instanceof LinearLayout) {
                        LinearLayout dayContainer = (LinearLayout) cell;

                        // 获取日期TextView（第0个child）和值班标识TextView（第1个child）
                        if (dayContainer.getChildCount() >= 2) {
                            View dayViewObj = dayContainer.getChildAt(0);
                            View dutyTagObj = dayContainer.getChildAt(1);
                            TextView textView = null;
                            TextView dutyTagView = null;

                            if (dayViewObj instanceof TextView) {
                                textView = (TextView) dayViewObj;
                            }
                            if (dutyTagObj instanceof TextView) {
                                dutyTagView = (TextView) dutyTagObj;
                            }

                            if (textView != null) {
                                // 直接从dayContainer获取CalendarDay对象
                                CalendarDay day = (CalendarDay) dayContainer.getTag();

                                if (day != null) {
                                    // 设置样式
                                    if (day.isCurrentMonth) {
                                        textView.setTextColor(getResources().getColor(R.color.color_1D2129));

                                        // 检查是否是今天
                                        boolean isToday = (day.year == todayYear && day.month == todayMonth && day.day == todayDay);

                                        // 检查是否是选中的日期
                                        boolean isSelected = (day.day == selectedDay);

                                        // 检查是否是值班日
                                        String dateStr = String.format(Locale.getDefault(), "%04d-%02d-%02d", day.year, day.month + 1, day.day);

                                        boolean isDutyDay = isDutyDay(dateStr);

                                        // 设置"值班日"标识
                                        if (isDutyDay) {
                                            if (dutyTagView != null) {
                                                dutyTagView.setVisibility(View.VISIBLE);
                                                dutyTagView.setText("值班日");
                                            }
                                        } else {
                                            if (dutyTagView != null) {
                                                dutyTagView.setVisibility(View.GONE);
                                            }
                                        }

                                        // 设置日期背景
                                        if (isToday) {

                                            // 值班日（非当天、非选中）：显示黄色背景
                                            android.graphics.drawable.GradientDrawable selectedBg = new android.graphics.drawable.GradientDrawable();
                                            selectedBg.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
                                            selectedBg.setCornerRadius(dpToPx(4));
                                            selectedBg.setColor(0x33165DFF); // 半透明蓝色
                                            dayContainer.setBackgroundDrawable(selectedBg);

                                            textView.setTextColor(getResources().getColor(R.color.white));
                                        } else if (isSelected) {
                                            // 选中（非当天）：显示半透明蓝色背景
                                            android.graphics.drawable.GradientDrawable selectedBg = new android.graphics.drawable.GradientDrawable();
                                            selectedBg.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
                                            selectedBg.setCornerRadius(dpToPx(4));
                                            selectedBg.setColor(0x330165FF); // 半透明蓝色
                                            dayContainer.setBackgroundDrawable(selectedBg);
                                            textView.setTextColor(getResources().getColor(R.color.radio_text_check_color));
                                        } else if (isDutyDay) {
                                            // 值班日（非当天、非选中）：显示黄色背景
                                            android.graphics.drawable.GradientDrawable selectedBg = new android.graphics.drawable.GradientDrawable();
                                            selectedBg.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
                                            selectedBg.setCornerRadius(dpToPx(4));
                                            selectedBg.setColor(0x330165FF); // 半透明蓝色
                                            dayContainer.setBackgroundDrawable(selectedBg);
                                            textView.setTextColor(getResources().getColor(R.color.white));
                                        } else {
                                            android.graphics.drawable.GradientDrawable defaultBg = new android.graphics.drawable.GradientDrawable();
                                            defaultBg.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
                                            defaultBg.setCornerRadius(dpToPx(4));
                                            defaultBg.setColor(getResources().getColor(R.color.white));
                                            dayContainer.setBackgroundDrawable(defaultBg);
                                        }
                                    } else {
                                        // 非当前月
                                        textView.setTextColor(getResources().getColor(R.color.light_gray));
                                        dayContainer.setBackground(null);
                                        if (dutyTagView != null) {
                                            dutyTagView.setVisibility(View.GONE);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 日历日期类
     */
    private static class CalendarDay {
        int year;
        int month;
        int day;
        boolean isCurrentMonth;

        CalendarDay(int year, int month, int day, boolean isCurrentMonth) {
            this.year = year;
            this.month = month;
            this.day = day;
            this.isCurrentMonth = isCurrentMonth;
        }
    }

    public static class DutyManagementStates extends StateHolder {
        public final State<String> monthYear = new State<>("");
        public final State<String> totalDutyDays = new State<>("共排班 0 天");
        public final State<Integer> selectedDay = new State<>(1);
        public final State<String> dutyStatus = new State<>("非值班日");
        public final State<String> dutyInfo = new State<>("");
        public final State<String> startTime = new State<>("");
    }

    public class ClickProxy {
        public void onDutyRecordsClick() {
            // 获取当前选中的日期
            int year = currentCalendar.get(Calendar.YEAR);
            int month = currentCalendar.get(Calendar.MONTH) + 1; // Calendar.MONTH从0开始
            int day = states.selectedDay.get();

            // 构建日期字符串
            String dateStr = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month, day);

            // 从list中查找对应日期的记录
            DutyManagerBean selectedDutyBean = null;
            if (list != null && !list.isEmpty()) {
                for (DutyManagerBean bean : list) {
                    if (bean.getStartDate() != null && bean.getStartDate().equals(dateStr)) {
                        selectedDutyBean = bean;
                        break;
                    }
                }
            }

            Intent intent = new Intent();
            intent.setClass(DutyManagementActivity.this, DutyRecordActivity.class);
            intent.putExtra("selectedDate", dateStr);
            intent.putExtra("selectedYear", year);
            intent.putExtra("selectedMonth", month);
            intent.putExtra("selectedDay", day);

            // 传递找到的记录数据
            if (selectedDutyBean != null) {
                // 直接传递对象
                intent.putExtra("dutyRecordData", selectedDutyBean);
            }

            startActivity(intent);
        }

        public void onMonthYearClick() {
            // 显示年月选择器
            showYearMonthPicker();
        }
    }

    /**
     * 显示年月选择器
     */
    private void showYearMonthPicker() {
        // 只显示年份和月份
        boolean[] type = new boolean[]{true, true, false, false, false, false};

        Calendar calendar = Calendar.getInstance();
        calendar.set(currentCalendar.get(Calendar.YEAR), currentCalendar.get(Calendar.MONTH), 1);

        TimePickerView mTimePickerView = new TimePickerView.Builder(DutyManagementActivity.this, (date, v) -> {
            Calendar selectedCal = Calendar.getInstance();
            selectedCal.setTime(date);

            int year = selectedCal.get(Calendar.YEAR);
            int month = selectedCal.get(Calendar.MONTH);

            currentCalendar.set(year, month, 1);
            states.monthYear.set(dateFormat.format(selectedCal.getTime()));
            states.selectedDay.set(1);

            generateCalendarDays(year, month);
            createCalendarView();

            // 重新加载数据
            states.startTime.set(String.format(Locale.getDefault(), "%04d-%02d", year, month + 1));
            String monthYearStr = String.format(Locale.getDefault(), "%04d-%02d", year, month + 1);
            mAccountRequester.scheduleList(UserInfo.getInstance().getProjectCode(), monthYearStr);
        })
                .isCyclic(false)
                .setRangDate(null, null)
                .setType(type)
                .setTitleText("选择月份")
                .setDate(calendar)
                .build();

        mTimePickerView.show();
    }
}

